<template>
  <div class="test-container">
    <div class="test-card">
      <h2>视频处理测试页面</h2>
      
      <div class="test-section">
        <h3>1. 选择测试视频</h3>
        <input type="file" @change="handleFileChange" accept="video/*" />
        <div v-if="selectedFile" class="file-info">
          已选择: {{ selectedFile.name }} ({{ formatFileSize(selectedFile.size) }})
        </div>
      </div>

      <div v-if="selectedFile" class="test-section">
        <h3>2. 测试方法</h3>
        <div class="test-buttons">
          <button @click="testFFmpegInit" :disabled="testing">测试 FFmpeg 初始化</button>
          <button @click="testVideoInfo" :disabled="testing || !selectedFile">测试获取视频信息</button>
          <button @click="testFrameExtraction" :disabled="testing || !selectedFile">测试帧提取</button>
          <button @click="testHTML5Method" :disabled="testing || !selectedFile">测试 HTML5 方法</button>
        </div>
      </div>

      <div v-if="testResults.length" class="test-section">
        <h3>3. 测试结果</h3>
        <div class="test-results">
          <div 
            v-for="(result, index) in testResults" 
            :key="index" 
            class="test-result"
            :class="result.type"
          >
            <div class="result-header">
              <strong>{{ result.title }}</strong>
              <span class="result-time">{{ result.timestamp }}</span>
            </div>
            <div class="result-content">{{ result.message }}</div>
            <pre v-if="result.data" class="result-data">{{ JSON.stringify(result.data, null, 2) }}</pre>
          </div>
        </div>
        <button @click="clearResults" class="clear-btn">清空结果</button>
      </div>

      <div v-if="testing" class="loading">
        <div class="spinner"></div>
        <div>{{ testingMessage }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { videoProcessor } from '@/utils/videoProcessor'

interface TestResult {
  type: 'success' | 'error' | 'info'
  title: string
  message: string
  timestamp: string
  data?: any
}

const selectedFile = ref<File | null>(null)
const testing = ref(false)
const testingMessage = ref('')
const testResults = ref<TestResult[]>([])

const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    selectedFile.value = target.files[0]
    addResult('info', '文件选择', `已选择文件: ${target.files[0].name}`)
  }
}

const addResult = (type: TestResult['type'], title: string, message: string, data?: any) => {
  testResults.value.unshift({
    type,
    title,
    message,
    timestamp: new Date().toLocaleTimeString(),
    data
  })
}

const testFFmpegInit = async () => {
  testing.value = true
  testingMessage.value = '正在初始化 FFmpeg...'
  
  try {
    videoProcessor.setProgressCallback((progress) => {
      testingMessage.value = progress.message
    })
    
    await videoProcessor.initialize()
    addResult('success', 'FFmpeg 初始化', 'FFmpeg 初始化成功！')
  } catch (error) {
    addResult('error', 'FFmpeg 初始化', `初始化失败: ${error instanceof Error ? error.message : '未知错误'}`, error)
  } finally {
    testing.value = false
  }
}

const testVideoInfo = async () => {
  if (!selectedFile.value) return
  
  testing.value = true
  testingMessage.value = '正在获取视频信息...'
  
  try {
    const info = await videoProcessor.getVideoInfo(selectedFile.value)
    addResult('success', '视频信息获取', '成功获取视频信息', info)
  } catch (error) {
    addResult('error', '视频信息获取', `获取失败: ${error instanceof Error ? error.message : '未知错误'}`, error)
  } finally {
    testing.value = false
  }
}

const testFrameExtraction = async () => {
  if (!selectedFile.value) return
  
  testing.value = true
  testingMessage.value = '正在提取视频帧...'
  
  try {
    const frames = await videoProcessor.extractFrames(selectedFile.value, 3)
    addResult('success', '帧提取', `成功提取 ${frames.length} 帧`, { frameCount: frames.length, frames: frames.map(f => f.substring(0, 50) + '...') })
    
    // 释放frame URLs
    frames.forEach(url => URL.revokeObjectURL(url))
  } catch (error) {
    addResult('error', '帧提取', `提取失败: ${error instanceof Error ? error.message : '未知错误'}`, error)
  } finally {
    testing.value = false
  }
}

const testHTML5Method = async () => {
  if (!selectedFile.value) return
  
  testing.value = true
  testingMessage.value = '正在使用 HTML5 方法处理...'
  
  try {
    const video = document.createElement('video')
    video.muted = true
    video.preload = 'metadata'
    
    const url = URL.createObjectURL(selectedFile.value)
    video.src = url
    
    await new Promise<void>((resolve, reject) => {
      video.onloadedmetadata = () => {
        const info = {
          duration: video.duration,
          width: video.videoWidth,
          height: video.videoHeight,
          readyState: video.readyState
        }
        
        addResult('success', 'HTML5 方法', '成功使用 HTML5 获取视频信息', info)
        URL.revokeObjectURL(url)
        video.remove()
        resolve()
      }
      
      video.onerror = () => {
        URL.revokeObjectURL(url)
        video.remove()
        reject(new Error('HTML5 video 加载失败'))
      }
      
      setTimeout(() => {
        URL.revokeObjectURL(url)
        video.remove()
        reject(new Error('HTML5 加载超时'))
      }, 10000)
    })
  } catch (error) {
    addResult('error', 'HTML5 方法', `处理失败: ${error instanceof Error ? error.message : '未知错误'}`, error)
  } finally {
    testing.value = false
  }
}

const clearResults = () => {
  testResults.value = []
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.test-container {
  max-width: 1000px;
  margin: 2rem auto;
  padding: 1rem;
}

.test-card {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.test-section {
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.test-section:last-child {
  border-bottom: none;
}

.file-info {
  margin-top: 0.5rem;
  padding: 0.5rem;
  background: #f0f9ff;
  border-radius: 4px;
  color: #0369a1;
}

.test-buttons {
  display: flex;
  gap: 1rem;
  flex-wrap: wrap;
}

.test-buttons button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  background: #3b82f6;
  color: white;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.test-buttons button:hover:not(:disabled) {
  background: #2563eb;
  transform: translateY(-1px);
}

.test-buttons button:disabled {
  background: #9ca3af;
  cursor: not-allowed;
  transform: none;
}

.test-results {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.test-result {
  padding: 1rem;
  border-bottom: 1px solid #f3f4f6;
}

.test-result:last-child {
  border-bottom: none;
}

.test-result.success {
  background: #f0fdf4;
  border-left: 4px solid #22c55e;
}

.test-result.error {
  background: #fef2f2;
  border-left: 4px solid #ef4444;
}

.test-result.info {
  background: #f0f9ff;
  border-left: 4px solid #3b82f6;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.result-time {
  font-size: 0.875rem;
  color: #6b7280;
}

.result-content {
  margin-bottom: 0.5rem;
}

.result-data {
  background: #1f2937;
  color: #f9fafb;
  padding: 0.75rem;
  border-radius: 4px;
  font-size: 0.875rem;
  overflow-x: auto;
  margin: 0;
}

.clear-btn {
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  cursor: pointer;
}

.clear-btn:hover {
  background: #f9fafb;
}

.loading {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: #f0f9ff;
  border-radius: 8px;
  margin-top: 1rem;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

h2 {
  margin-bottom: 2rem;
  color: #1f2937;
}

h3 {
  margin-bottom: 1rem;
  color: #374151;
}
</style> 